<?php
namespace app\model\user;

use think\Model;
use app\model\product\ZxlKnowStoreProductModel;

class ZxlKnowStorePowerModel extends Model
{
    protected $name = 'zxl_know_store_power';

    /**
     * 权限详情
     *
     * @param [type] $product_id 产品ID
     * @param [type] $user_id 用户ID
     * @param string $channel 渠道
     * @return integer 0 未开通 1 已开通或者纯免费
     */
    public static function getPowerDetail($product_id, $user_id, $channel = "know_store") :int{
        $powerAuth = 0;
        if ($user_id) {
            if($channel == 'college')  {
                $powerAuth = 1;
            } else {
                $power = ZxlKnowStorePowerModel::where(['product_id' => $product_id, 'user_id' => $user_id, 'is_delete' => 0])
                ->where(function($q){
                    $q->whereOr('end_time', 0)
                    ->whereOr('end_time', '>', time());
                })->findOrEmpty();
                if($power->isEmpty()){
                    $producInfo = ZxlKnowStoreProductModel::with(['specs'=>function($q){
                        $q->where('is_delete', 0)->where('status', 1);
                    }])->where('id', $product_id)->find();
                    if($producInfo && $producInfo->product_type == 5){
                        foreach ($producInfo->specs as $attr) {
                            if($attr['sale_price'] <= 0) {
                                $powerAuth = 1;
                                break;
                            }
                        }
                    } 
                } else $powerAuth = 1;
            }
        }
        return $powerAuth;
    }
}